<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage } from "element-plus";

const searchKeyword = ref('')
const searchDepartment = ref('')
const selectedDepartment = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const departments = ['销售部', '技术部', '人力资源部', '财务部']

const filteredData = computed(() => {
  if (!Array.isArray(tableData)) return []
  return tableData.filter(item => {
    const  matchesName = !searchKeyword.value || item.sign.includes(searchKeyword.value)
    const  matchesDepartment = !selectedDepartment.value || item.department === selectedDepartment.value
    return matchesName && matchesDepartment
  })
})
const handleSearch = () =>{
  console.log('搜索条件:', {
    name: searchKeyword.value,
    department: searchDepartment.value
  })
}
const resetSearch = () =>{
  searchKeyword.value = ''
  //searchDepartment.value = ''
  selectedDepartment.value = ''
}
const selectedItems = ref<Record<string, any>[]>([])
const exportToCSV = (data: Record<string, any>[], filename: string)=>{
  if (data.length === 0) return;
  // 定义CSV表头
  const headers = ['序号', '签到人', '签到地点', '签到时间', '所属部门'];
  const fields = ['id', 'sign', 'locations', 'time', 'department'];

  // 构建CSV内容
  let csvContent = '\uFEFF' + headers.join(',') + '\n'; // 添加UTF-8 BOM
  // 添加数据行
  data.forEach(item => {
    const row = fields.map(field => {
      const value = item[field];
       let processedValue = value;
      if (field === 'time' && processedValue instanceof Date) {
        processedValue = processedValue.toISOString().replace('T', ' ').substring(0, 16);
      }
      // 处理包含逗号或引号的值
      if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
        return `"${value.replace(/"/g, '""')}"`;
      }
      return value;
    }).join(',');
    csvContent += row + '\n';
  });

  // 创建Blob对象
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  // 设置文件名
  const dateTime = new Date().toISOString().slice(0, 10);
  link.setAttribute('href', url);
  link.setAttribute('download', `${filename}_${dateTime}.csv`);
  link.style.visibility = 'hidden';

  // 触发下载
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

}
const handleSelectionChange = (selection: Record<string, any>[]) => {
  selectedItems.value = selection;
};
const handleExport = () => {
 if (selectedItems.value.length === 0){
   ElMessage.warning('请至少选择一条数据')
    return
 }
 const size =selectedItems.value.length
 ElMessage.success(`已选择${size}条数据，正在导出...`)
   //console.log('导出数据:', selectedItems.value)
  // 实际项目中可以使用以下方式导出为CSV
  //exportToCSV(selectedItems.value, '签到信息');
  exportToCSV(selectedItems.value, '签到信息')
};

// 数据
const tableData = reactive(
    [
      {
        id: 1,
        sign: '小明',
        time: '2024-09-09 16:36',
        locations: '北京市海淀区',
        department: '销售部',
      },{
      id: 2,
      sign: '小兰',
      time: '2024-09-09 16:36',
      locations: '北京市海淀区',
      department: '技术部',
    },{
      id: 3,
      sign: '小龙',
      time: '2024-09-09 16:36',
      locations: '北京市海淀区',
      department: '人力资源部',
    },{
      id: 4,
      sign: '小萌',
      time: '2024-09-09 16:36',
      locations: '北京市海淀区',
      department: '财务部',
    },
    ]
)
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}
function handleCurrentChange(val) {
  currentPage.value = val
}
</script>

<!-- 签到信息 -->
<template>
  <div class="container">
    <el-card shadow="always" class="main-card">
      <div class="header-section">
        <span class="title">签到信息</span>
      </div>
      <div class="search-section">
          <el-input v-model="searchKeyword" placeholder="签到人姓名" class="mobile-full-width" />
          <el-select v-model="selectedDepartment" placeholder="部门" class="mobile-full-width">
            <el-option v-for="dept in departments" :key="dept" :label="dept" :value="dept" />
          </el-select>
          <el-button  type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch" >重置</el-button>
          <el-button type="info" class="export-button" @click="handleExport">导出</el-button>
      </div>
      <div class="table-wrapper">
        <el-table :data="filteredData" border style="width: 100%" :header-cell-style="{ textAlign: 'center' }"
                  :cell-style="{ textAlign: 'center' }" class="sign-table" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50"/>
          <el-table-column prop="id" label="序号" />
          <el-table-column prop="sign" label="签到人" />
          <el-table-column prop="locations" label="签到地点" />
          <el-table-column prop="time" label="签到时间" />
          <el-table-column prop="department" label="所属部门" />
        </el-table>
      </div>
      <div class="pagination-wrapper">
        <el-pagination size="small"
                       background
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="filteredData .length"
                       :page-sizes="[10, 20, 50, 100]"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       class="mt-4" />
      </div>
    </el-card>
  </div>
</template>

<style>
.header-section{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}
.search-section {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}
.mobile-full-width{
  flex: 1;
  min-width: 120px;
}
.title{
  font-size: 20px;
  font-weight: bold;
}
@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .mobile-full-width {
    min-width: auto;
  }
}
</style>


